package com.agnes.okhttp.lib;

import android.text.TextUtils;

import com.agnes.okhttp.lib.util.JsonUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.log.LoggerInterceptor;
import com.zhy.http.okhttp.request.RequestCall;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class OkUtils {
    private static OkUtils mInstance;
    private long timedOut;

    private OkUtils() {
    }

    public static OkUtils getInstance() {
        if (mInstance == null) {
            synchronized (OkUtils.class) {
                if (mInstance == null) {
                    mInstance = new OkUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * 全局初始化 OkHttpClient
     */
    public void init() {
        LoggerInterceptor loggerInterceptor = new LoggerInterceptor("OkUtils", true);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)
                .readTimeout(1, TimeUnit.MINUTES)
                .writeTimeout(1, TimeUnit.MINUTES)
                .addInterceptor(loggerInterceptor)
                .build();
        com.zhy.http.okhttp.OkHttpUtils.initClient(okHttpClient);
    }


    public OkUtils setTimedOut(long timedOut) {
        this.timedOut = timedOut;
        return this;
    }


    /**
     * @param url      完整url
     * @param callback
     */
    public void get(String url, Callback callback) {
        if (TextUtils.isEmpty(url)) return;

        RequestCall requestCall = OkHttpUtils.get()
                .url(url)
                .build();

        execute(requestCall, callback);
    }


    /**
     * @param url      请求地址
     * @param t        Map or  实体
     * @param callback 回调
     * @param <T>
     */
    public <T> void post(String url, T t, Callback callback) {
        if (TextUtils.isEmpty(url)) return;

        String content = JsonUtils.toJson(t);

        RequestCall requestCall = OkHttpUtils.postString()
                .url(url)
                .mediaType(NetConst.MEDIA_TYPE_JSON)
                .content(content)
                .build();

        execute(requestCall, callback);


    }


    private void execute(RequestCall requestCall, Callback callback) {
        if (timedOut > 0) {
            requestCall.connTimeOut(timedOut);
            requestCall.readTimeOut(timedOut);
            requestCall.writeTimeOut(timedOut);
        }

        requestCall.execute(callback);
    }

}
